package setting

import (
	"fmt"
	"github.com/fsnotify/fsnotify"
	"github.com/spf13/viper"
	"go.uber.org/zap"
)

var Conf = new(AppConfig)

type AppConfig struct {
	Name         string `mapstructure:"name"`
	Mode         string `mapstructure:"mode"`
	Port         int    `mapstructure:"port"`
	StartTime    string `mapstructure:"start_time"`
	MachineID    int64  `mapstructure:"machine_id"`
	*LogConfig   `mapstructure:"log"`
	*MysqlConfig `mapstructure:"mysql"`
	*RedisConfig `mapstructure:"redis"`
}
type LogConfig struct {
	Level      string `mapstructure:"level"`
	Filename   string `mapstructure:"filename"`
	MaxSize    int    `mapstructure:"max_size"`
	MaxAge     int    `mapstructure:"max_age"`
	MaxBackups int    `mapstructure:"max_backups"`
}
type MysqlConfig struct {
	Host               string `mapstructure:"host"`
	Port               int    `mapstructure:"port"`
	User               string `mapstructure:"user"`
	Password           string `mapstructure:"password"`
	Dbname             string `mapstructure:"dbname"`
	MaxLifeSeconds     int    `mapstructure:"max_life_seconds"`
	MaxIdleConnections int    `mapstructure:"max_idle_connections"`
	MaxOpenConnections int    `mapstructure:"max_open_connections"`
	Charset            string `mapstructure:"charset"`
}

type RedisConfig struct {
	Host        string `mapstructure:"host"`
	Port        int    `mapstructure:"port"`
	Password    string `mapstructure:"password"`
	PoolSize    int    `mapstructure:"poolSize"`
	MinIdleConn int    `mapstructure:"minIdleConn"`
	DB          int    `mapstructure:"db"`
}

func Init(filePath string) (err error) {
	viper.SetConfigFile(filePath) // 指定配置文件路径
	err = viper.ReadInConfig()    // 读取配置信息
	if err != nil {               // 读取配置信息失败
		zap.L().Error("viper.ReadInConfig() failed", zap.Error(err))
		return err
	}
	if err := viper.Unmarshal(Conf); err != nil {
		zap.L().Error("viper.Unmarshal failed,err:%v", zap.Error(err))
	}
	// 监控配置文件变化
	viper.WatchConfig()

	viper.OnConfigChange(func(in fsnotify.Event) {
		fmt.Println("配置文件修改了")
		if err := viper.Unmarshal(Conf); err != nil {
			zap.L().Error("viper.Unmarshal failed,err:%v", zap.Error(err))
		}
	})
	return err
}
